package org.lanyu.springainovel;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Spring Boot主应用类
 */
@SpringBootApplication
@EnableScheduling
@MapperScan({ "org.lanyu.springainovel.**.mapper"})
public class SpringaiNovelApplication implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${server.port:8080}")
    private String serverPort;

    public SpringaiNovelApplication() { super(); }

    public static void main(String[] args) {
        SpringApplication springApplication=new SpringApplication(SpringaiNovelApplication.class);
        //设置它的属�?屏蔽logo打印
        springApplication.setBannerMode(Banner.Mode.OFF);
        springApplication.run(args);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            String localIp = getLocalIp();
            System.out.println("Knife4j接口文档地址: http://" + localIp + ":" + serverPort + "/doc.html");
        } catch (Exception e) {
            System.out.println("Knife4j接口文档地址: http://localhost:" + serverPort + "/doc.html");
        }
    }

    /**
     * 获取内网IP地址
     */
    private String getLocalIp() throws SocketException {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            // 跳过回环接口、虚拟接口等
            if (networkInterface.isLoopback() || !networkInterface.isUp() || networkInterface.isVirtual()) {
                continue;
            }

            Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                // 只获取IPv4地址
                if (!address.isLoopbackAddress() && address.getHostAddress().indexOf(':') == -1) {
                    String ip = address.getHostAddress();
                    // 过滤�?69.254开头的链路本地地址
                    if (!ip.startsWith("169.254.")) {
                        return ip;
                    }
                }
            }
        }
        return "localhost";
    }
}
